class AccountController < ApplicationController   

  before_filter :login_required, :except => ['login', 'index', 'signup', 'forgot_password', 'reset_password', 'activate', 'accept_invitation']  
  
  # say something nice, you goof!  something sweet.
  def index  
    
    if logged_in?
      redirect_to :controller => "workitem", :action => 'list'
      return
    else 
      redirect_to :action => 'login'
      return
    end
    
  end
  
  def list
    @accounts = User.find(:all, :include => ['roles', 'site'], :order => "last_name")
#    @account_pages, @accounts = paginate :user, :per_page => 10, :include => ['roles', 'site'], :order_by=> "last_name"
  end

  def login
    return unless request.post?
    self.current_user = User.authenticate(params[:email], params[:password])
    if logged_in?  
      # set last_login
      self.current_user.update_attribute(:last_login, Time.now)
      if params[:remember_me] == "1"
        self.current_user.remember_me
        cookies[:auth_token] = { :value => self.current_user.remember_token , :expires => self.current_user.remember_token_expires_at }
      end
      redirect_back_or_default(:controller => '/account', :action => 'index')
      flash[:notice] = "Logged in successfully"
    else
      flash[:notice] = "Invalid email address or password, please try again."
    end  
    
  end

  def signup
    @user = User.new(params[:user])
    return unless request.post?
    @user.save!        
    role = Role.find_by_name("Seeker");
    role.users << @user
    role.save!
    flash[:notice] = "Thanks for signing up! To activate your account, check your email, and click on the link inside the email."
    redirect_back_or_default(:controller => '/account', :action => 'login')
  rescue ActiveRecord::RecordInvalid
    render :action => 'signup'
  end
  
  def logout
    self.current_user.forget_me if logged_in?
    cookies.delete :auth_token
    reset_session
    flash[:notice] = "You have been logged out."
    redirect_back_or_default(:controller => '/account', :action => 'login')
  end   
  
  def forgot_password
    return unless request.post?
    param_user = User.new(params[:user])
    if @user = User.find_by_email(param_user.email)
      @user.forgot_password
      @user.save
      flash[:notice] = "A password reset link has been sent to your email address" 
      redirect_back_or_default(:controller => '/account', :action => 'login')
    else
      flash[:notice] = "Could not find a user with that email address" 
    end
  end

  def reset_password
    @user = User.find_by_password_reset_code(params[:id])
    raise if @user.nil?
    return if @user unless params[:password]

    if (params[:password] == params[:password_confirmation])
      self.current_user = @user #for the next two lines to work
      current_user.password_confirmation = params[:password_confirmation]
      current_user.password = params[:password]
      @user.reset_password
      flash[:notice] = current_user.save ? "Password reset" : "Password not reset"   
      self.current_user = nil 
      redirect_back_or_default(:controller => '/account', :action => 'login') 
    else
      flash[:notice] = "Password mismatch"                                    
    end  

    rescue
      logger.error "Invalid Reset Code entered" 
      flash[:notice] = "Sorry - That is an invalid password reset code. Please check your code and try again. (Perhaps your email client inserted a carriage return?" 
      redirect_back_or_default(:controller => '/account', :action => 'login')
  end
      
  def activate
    @user = User.find_by_activation_code(params[:id])
    if @user and @user.activate
      redirect_back_or_default(:action => 'login')
      flash[:notice] = "Your account has been activated." 
    end
  end  
  
  
  def change_password
    
    # forward to view if this is not a post.
    return unless request.post?
    
    # verify that the old_password is correct
    if User.authenticate(current_user.email, params[:old_password]) 
      
      # if the password or password_confirmation is empty, then don't go any further.
      if params[:password_confirmation].empty? || params[:password].empty?
        flash[:notice] = "password not updated"                                      
        
      # if the password and password confirmation are equal, then change the password.  
      elsif ((params[:password] == params[:password_confirmation]))
        current_user.password_confirmation = params[:password_confirmation]
        current_user.password = params[:password]                                     
        
        # TODO: this does not provide a specific reason why the password did not change.
        flash[:notice] = current_user.save ?
              "Password changed" :
              "Password not changed"                                                    
              
      # get out of here.
      else
        flash[:notice] = "Password mismatch" 
        @old_password = params[:old_password]
      end
    else
      flash[:notice] = "Wrong password" 
    end
  end 
  
  def show
    @user = User.find(params[:id])
  end 
  
  def edit
    @user = User.find(params[:id])
    @roles = Role.find(:all)
  end     
  
  def invite 
    @user = User.new(params[:user])
    return unless request.post?
    @user.activated_at = Time.now 
    @user.password = Digest::SHA1.hexdigest( Time.now.to_s.split(//).sort_by {rand}.join )
    @user.password_confirmation = @user.password
    @user.invite
    @user.save!          
    flash[:notice] = "Invitation has been sent to #{@user.display_name}."
    redirect_back_or_default(:controller => '/account', :action => 'list')
  rescue ActiveRecord::RecordInvalid
    redirect_to :action => 'list'
  end 
  
  def accept_invitation
    redirect_to :action => 'reset_password', :id => params[:id]
  end

  def update
    @user = User.find(params[:id])
    if @user.update_attributes(params[:user])
      flash[:notice] = 'User was successfully updated.'
      redirect_to :action => 'show', :id => @user
    else
      render :action => 'edit'
    end
  end

end
